package com.it.you.base.tree;

import java.util.Stack;

public class BinaryTree {

    Node root;

    // 插入元素
    void put(int value) {
        if (root == null) {
            root = new Node(value);
        } else {
            Node parent = root;
            while (true) {
                if (value <= parent.value) {
                    if (parent.left == null) {
                        parent.left = new Node(value);
                        return;
                    } else {
                        parent = parent.left;
                    }
                } else {
                    if (parent.right == null) {
                        parent.right = new Node(value);
                        return;
                    } else {
                        parent = parent.right;
                    }
                }

            }
        }
    }

    // 先序遍历
    void preTraversal(Node x) {
        if (x == null) return;
        System.out.print(x.value + ",");
        preTraversal(x.left);
        preTraversal(x.right);
    }

    static class Node {
        int value;
        Node left;
        Node right;

        public Node(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        binaryTree.put(3);
        binaryTree.put(1);
        binaryTree.put(2);
        binaryTree.put(7);
        binaryTree.put(8);
        binaryTree.put(5);
        binaryTree.put(4);
        binaryTree.put(6);
        binaryTree.put(9);
        binaryTree.put(0);

        binaryTree.preTraversal(binaryTree.root);
    }

    // 先序遍历非递归形式
    void nonRecursivePreTraversal(Node x) {
        // 自己模拟一个栈
        Stack<Node> stack = new Stack<Node>();
        stack.push(x);
        while (!stack.isEmpty()) {
            Node tmp = stack.pop();
            // 隐含的边界条件
            if (tmp != null) {
                System.out.print(tmp.value + ",");
                // 缩小问题规模
                stack.push(tmp.right);
                stack.push(tmp.left);
            }
        }
    }
}
